package com.wms.service.impl;

import com.wms.mapper.TuPianMapper;
import com.wms.minio.MinioPojo;
import com.wms.service.TuPianService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class TuPianServiceImpl implements TuPianService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioPojo minio;
    @Autowired
    TuPianMapper tuPianMapper;

    @Transactional
    @Override
    public String upload(String bucketName, MultipartFile file) {
        try {
            boolean exists =minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            //如果桶不存在，创建桶
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            //获取时间
            String dateTime =
                    LocalDateTime.now().format(DateTimeFormatter
                            .ofPattern("yyyy-MM-dd"));
            //UUID
            String uuid = UUID.randomUUID().toString();
            //获取文件名
            String originalFilename =
                    file.getOriginalFilename();
            String extension
                    =originalFilename.substring(originalFilename
                    .lastIndexOf("."));
            String newFileName = uuid +
                    extension;
            String fileName = dateTime + "/" +
                    newFileName;

            minioClient.putObject(PutObjectArgs.builder
                            ()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(file.getInputStream(),
                            file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());
            String url = minio.getUrl() + "/" +
                    bucketName + "/" + fileName;

            //插入图片信息
            tuPianMapper.insertImg(url,url);

            return url;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败");
        }
    }

    //查询图片信息
    @Override
    public List<Map> selectTu() {
       List<Map> list= tuPianMapper.tuPianService();
    return list;
    }
}
